package com.foreveross.fetl.queue;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.log4j.Logger;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import com.common.remote.ftp.FtpConfig;
import com.common.remote.ftp.FtpTransferException;
import com.common.remote.sftp.SFtpFileTransferClient;
import com.dayatang.domain.InstanceFactory;
import com.foreveross.fetl.application.ITaskTimeApplication;
import com.foreveross.fetl.common.cfg.system.ReportProperties;
import com.foreveross.fetl.common.hbase.client.HBaseHelper;
import com.foreveross.fetl.core.domain.task.SourceEntity;
import com.foreveross.fetl.queue.util.HangxinDateUtil;
import com.foreveross.fetl.util.AirLinesData;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.FetlErrorUtils;
import com.foreveross.fetl.util.PriceUtil;
import com.foreveross.fetl.util.RowkeyUtils;
import com.foreveross.fetl.util.StringUtils;
import com.foreveross.fetl.util.ZipUtils;
import com.foreveross.fetl.vo.TaskTimeVO;

@Component
public class MetadataCountPreprocess {
	
	private static Logger log = Logger.getLogger("count");
	
	public Map<String,String> mapChannel= new HashMap<String,String>();
	
	private void setChannelName(){
		SourceEntity entity=new SourceEntity();
		for(SourceEntity en:entity.findAll()){
			mapChannel.put(en.getHbaseKey(), en.getShortName());
		}
	}
	
	public void countforExcel(Date start,Date endTime){
		Map<String,List<String>> map =AirLinesData.getDoubleMapAirLines().get("hangxin");
		Set<Date> flightDateSet=HangxinDateUtil.getFlightDateSet();
		Map<String,Map<String,Map<String,Map<String,Integer>>>> countMap =new LinkedHashMap<String,Map<String,Map<String,Map<String,Integer>>>>();
		for(String hbaseKey:map.keySet()){
			Map<String,Map<String,Map<String,Integer>>> count=this.countALL(start, endTime,hbaseKey,map.get(hbaseKey),flightDateSet,true);
			countMap.put(hbaseKey, count);
		}
		File file=null;

			try {
				file=this.createHangxinFile(endTime,countMap);
				this.uploadFile(file, "hangxin/excel");
			} catch (Exception e) {
				log.error(StringUtils.getStackTrace(e));
			}finally{
				file.delete();
			}
			try {
				file=this.createCountFile(endTime,countMap);
				this.uploadFile(file, "hangxin/excel");
			} catch (Exception e) {
				log.error(StringUtils.getStackTrace(e));
			}finally{
				file.delete();
			}
		
	}
	
	public void countforExcel(Date date){
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(date);
		int hour =calendar.get(Calendar.HOUR_OF_DAY);
		List<TaskTimeVO> listTask=null;
		Map<String,List<String>> map =AirLinesData.getDoubleMapAirLines().get("hangxin");
		Set<Date> flightDateSet=HangxinDateUtil.getFlightDateSet();
		Map<String,Map<String,Map<String,Map<String,Integer>>>> countMap =new LinkedHashMap<String,Map<String,Map<String,Map<String,Integer>>>>();
		for(String hbaseKey:map.keySet()){
			listTask=InstanceFactory.getInstance(ITaskTimeApplication.class).find(hbaseKey, FetlErrorUtils.metadataForAirs, hour);
			if(null!=listTask && listTask.size()>0){
				TaskTimeVO vo= listTask.get(0);
				String dateStr=DateUtils.format(new Date(), "yyyyMMdd");
				String start=null;
				String end=null;
				if(vo.getGrabStart()<10)
					start=dateStr+"0"+vo.getGrabStart();
				else
					start=dateStr+vo.getGrabStart();
				
				if(vo.getGrabStop()<10)
					end=dateStr+"0"+vo.getGrabStop();
				else
					end=dateStr+vo.getGrabStop();
				
				Date sTime=DateUtils.parse(start, "yyyyMMddHH");
				Date eTime=DateUtils.parse(end, "yyyyMMddHH");
				Map<String,Map<String,Map<String,Integer>>> count=this.countALL(sTime, eTime,hbaseKey,map.get(hbaseKey),flightDateSet,true);
				countMap.put(hbaseKey, count);
			}else{
				Map<String,Map<String,Map<String,Integer>>> count=this.countALL(null, null,hbaseKey,map.get(hbaseKey),flightDateSet,false);
				countMap.put(hbaseKey, count);
			}
			
		}
		
		File file=null;
		try {
			file=this.createCountFile(new Date(),countMap);
			this.uploadFile(file, "hangxin/excel");
		} catch (Exception e) {
			log.error(StringUtils.getStackTrace(e));
		}finally{
			if(null!=file && file.exists())
				file.delete();
		}
		try {
			file=this.createHangxinFile(new Date(),countMap);
			this.uploadFile(file, "hangxin/excel");
		} catch (Exception e) {
			log.error(StringUtils.getStackTrace(e));
		}finally{
			if(null!=file && file.exists())
				file.delete();
		}
	}
	






	/**
	 * 统计一个渠道的数量
	 * @param start
	 * @param endTime
	 * @param hbaseKey
	 * @param list
	 * @param flightDateSet
	 * @return
	 */
	private Map<String, Map<String, Map<String, Integer>>> countALL(Date start,
			Date endTime, String hbaseKey, List<String> list,
			Set<Date> flightDateSet,boolean iscount) {
		Integer[] returnDays=HangxinDateUtil.getReturnDays();
		Map<String, Map<String, Map<String, Integer>>> lineMap =new LinkedHashMap<String, Map<String, Map<String, Integer>>>();
		//2015年春节期间
		Date chineseNewYear=DateUtils.parse("20150212", "yyyyMMdd");
		Calendar chnew=Calendar.getInstance();
		chnew.setTime(chineseNewYear);
		
		Calendar chnewEnd=Calendar.getInstance();
		chnewEnd.setTime(chineseNewYear);
		chnewEnd.add(Calendar.DAY_OF_MONTH, 8);
		
		for(String line:list){
			Map<String, Map<String, Integer>> flightDateMap= new LinkedHashMap<String, Map<String, Integer>>();
			for(Date flightDate:flightDateSet){
				
				Map<String, Integer> returnDateMap=new LinkedHashMap<String, Integer>();
				for(int i=0;i<returnDays.length;i++){
					Calendar c =Calendar.getInstance();
					c.setTime(flightDate);
					if(c.after(chnew) && c.before(chnewEnd) && i==2){
						continue;
					}
						
					c.add(Calendar.DAY_OF_MONTH, returnDays[i]);
					Date returnFlightDate=c.getTime();
					int count=-1;
					if(iscount){
						count=this.count(start,endTime,hbaseKey,line,flightDate,returnFlightDate);
					}
					returnDateMap.put(DateUtils.format(returnFlightDate, "yyyy-MM-dd"), count);
				}
				flightDateMap.put(DateUtils.format(flightDate, "yyyy-MM-dd"), returnDateMap);
			}
			lineMap.put(line, flightDateMap);
		}
		return lineMap;
	}
	
	/**
	 * 统计 hbase里符合条件的数量
	 * @param start
	 * @param endTime
	 * @param hbaseKey
	 * @param line
	 * @param flightDate
	 * @param returnFlightDate
	 * @return
	 */
	private int count(Date start, Date endTime,String hbaseKey, String line, Date flightDate,
			Date returnFlightDate) {
		int count=0;
		ResultScanner rs = null;
		String[] citys=line.split("-");
		Calendar cStart = Calendar.getInstance();
		cStart.setTime(start);
		Calendar cEnd = Calendar.getInstance();
		cEnd.setTime(endTime);
		String flightDateStr=DateUtils.format(flightDate, "yyyyMMdd");
		String returnFlightDateStr=DateUtils.format(returnFlightDate, "yyyyMMdd");
		while (cStart.before(cEnd)) {
			String timeStr=DateUtils.format(cStart.getTime(), "yyyyMMddHH");
			String startRow=RowkeyUtils.getDoubleRowKey(timeStr, hbaseKey, citys[0],citys[1], flightDateStr,
					returnFlightDateStr, null, RowkeyUtils.START_ROW_KEY);
			String endRow=RowkeyUtils.getDoubleRowKey(timeStr, hbaseKey, citys[0],citys[1], flightDateStr,
					returnFlightDateStr, null, RowkeyUtils.STOP_ROW_KEY);
			try {
				try {
					rs = HBaseHelper.getRecords("CRAWL_PLANE_FREIGHT_DOUBLE",
							startRow, endRow,new String[]{"planeinfo"},null);
					
				} catch (Exception e) {
					rs = HBaseHelper.getRecords("CRAWL_PLANE_FREIGHT_DOUBLE",
							startRow, endRow,new String[]{"planeinfo"},null);
					
					//如果从hbase里读数据失败了就再来一次
				}
				int i=0;
				for (Result res : rs) {
					i++;
				}
				count+=i;
			} catch (IOException e) {
				log.error(StringUtils.getStackTrace(e));
			}finally{
				if(rs != null) rs.close();
				rs = null;
			}
			cStart.add(Calendar.HOUR_OF_DAY, 1);// 开始时间加一小时
		}
		
		return count;
	}
	
	private File createCountFile(Date endTime,
			Map<String, Map<String, Map<String, Map<String, Integer>>>> countMap) {
		
		Calendar c= Calendar.getInstance();
		int week=c.get(Calendar.DAY_OF_WEEK);
		int weekOfMonth =c.get(Calendar.WEEK_OF_MONTH);
		if(week==1 && weekOfMonth>1){
			weekOfMonth--;
		}
		String fileName= "hangxinReturn_"+DateUtils.format(endTime, "yyyy-MM")+"_"+weekOfMonth+".xlsx";
		String remotePath="hangxin/excel/";
		File file=null;
		file=this.downloadFile(remotePath, fileName);
		XSSFWorkbook  workbook = null;
		OutputStream os = null;
		FileInputStream is =null;
		try {
			if(null==file || !file.exists()){
				workbook = new XSSFWorkbook();
			}else{
				is= new FileInputStream(file.getPath());
				workbook = new XSSFWorkbook(is);
			}
			
			XSSFSheet sheet = workbook.createSheet(DateUtils.format(new Date(), "yyyy-MM-dd HHmm"));
			String[] title ={"渠道","出发城市","到达城市","出发日期","返程日期","天数","数量"};
			XSSFRow row = sheet.createRow(0);
	        for(int i=0;i<title.length;i++){
	        	XSSFCell cell = row.createCell(i);
	        	cell.setCellValue(title[i]);
	        }
	        int column=1;
	        Integer[] returnDays=HangxinDateUtil.getReturnDays();
	        XSSFRow   rows =null;
	        XSSFCell cell=null;
	        for(String channel:countMap.keySet()){
	        	for(String line:countMap.get(channel).keySet()){
	        		String[] citys=line.split("-");
	        		for(String flightDate:countMap.get(channel).get(line).keySet()){
	        			int days=0;
	        			for(String returnDate: countMap.get(channel).get(line).get(flightDate).keySet()){
	        				 rows = sheet.createRow(column);
	        				 cell=rows.createCell(0);
	        				 cell.setCellValue(channel);
	        				
	        				 cell=rows.createCell(1);
	        				 cell.setCellValue(citys[0]);
	        				
	        				 cell=rows.createCell(2);
	        				 cell.setCellValue(citys[1]);
	        				 
	        				 cell=rows.createCell(3);
	        				 cell.setCellValue(flightDate);
	        				 
	        				 cell=rows.createCell(4);
	        				 cell.setCellValue(returnDate);
	        				 
	        				 cell=rows.createCell(5);
	        				 cell.setCellValue(returnDays[days]);
	        				  
	        				 cell=rows.createCell(6);
	        				 cell.setCellValue(countMap.get(channel).get(line).get(flightDate).get(returnDate));
	        				 column++;
	        				 days++;
	        			}
	        		}
	        	}
	        }
	        if(null!=is){
	        	is.close();
	        }
	        if(null==file || !file.exists()){
	        	 file=new File(fileName);
	        }
	        os = new FileOutputStream(file); 
	        workbook.write(os);
	        os.close();
	        
		} catch (Exception e) {
			log.error(StringUtils.getStackTrace(e));
		}finally{
			if(null!=os){
				try {
					os.close();
				} catch (IOException e) {
					log.error(StringUtils.getStackTrace(e));
				}
			}
		}
		return file;
	}
	
	private File createHangxinFile(Date endTime,
			Map<String, Map<String, Map<String, Map<String, Integer>>>> countMap) {
		
		File file =null;
		Calendar c= Calendar.getInstance();
		int week=c.get(Calendar.DAY_OF_WEEK);
		
		int weekOfMonth =c.get(Calendar.WEEK_OF_MONTH);
		if(week==1 && weekOfMonth>1){
			weekOfMonth--;
		}
		
		String fileName="hangxin_"+DateUtils.format(endTime, "yyyyMM")+"_"+weekOfMonth+".xlsx";
		
		
		String remotePath="hangxin/excel/";
		file=this.downloadFile(remotePath, fileName);

		XSSFWorkbook  workbook = null;
		OutputStream os = null;
		XSSFSheet sheet =null;
		FileInputStream is =null;
		try {
			if(null==file || !file.exists()){
				workbook = new XSSFWorkbook();
			}else{
				is= new FileInputStream(file.getPath());
				workbook = new XSSFWorkbook(is);
			}
			 int sheetSize=workbook.getNumberOfSheets();	
			 if(sheetSize==0){
				 sheet = workbook.createSheet("中航信抓取统计");
				 sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));
				 XSSFRow row = sheet.createRow(0);
				 XSSFCell cell = row.createCell(0);
				 cell.setCellValue("站点");
				 
				 sheet.addMergedRegion(new CellRangeAddress(0,0,1,2));
				 cell = row.createCell(1);
				 cell.setCellValue("航线");
				 
				 row = sheet.createRow(1);
				 cell = row.createCell(1);
				 cell.setCellValue("出发城市");
				 
				 cell = row.createCell(2);
				 cell.setCellValue("到达城市");
				 
				 sheet.createRow(2);
				 
				 int column=3;
				 setChannelName();
				 for(String channel:countMap.keySet()){
					 int i=0;
					 for(String line:countMap.get(channel).keySet()){
						 String[] citys=line.split("-");
						 row = sheet.createRow(column);
						 if(i==0){
							 cell=row.createCell(0);
	        				 cell.setCellValue(channel);
	        				 i++;
						 }
						 if(i==1){
							 cell=row.createCell(0);
	        				 cell.setCellValue(null==mapChannel.get(channel)?channel:mapChannel.get(channel));
	        				 i++; 
						 }
        				 cell=row.createCell(1);
        				 cell.setCellValue(citys[0]);
        				
        				 cell=row.createCell(2);
        				 cell.setCellValue(citys[1]);
        				 column++;
					 }
				 }
				 for(String channel:countMap.keySet()){
					 row = sheet.createRow(column);
					 cell=row.createCell(0);
					 cell.setCellValue(null==mapChannel.get(channel)?channel:mapChannel.get(channel)+"小计");
					 column++;
					 row = sheet.createRow(column);
					 cell=row.createCell(0);
					 cell.setCellValue("完成率");
					 column++;
				 }
				 row = sheet.createRow(column);
				 cell=row.createCell(0);
				 cell.setCellValue("合计");
				 column++;
				 row = sheet.createRow(column);
				 cell=row.createCell(0);
				 cell.setCellValue("完成率");
				
			 }else{
				 sheet = workbook.getSheetAt(0);  
			 }
			 
		
		 XSSFCellStyle redStyle = workbook.createCellStyle();
		 redStyle.setFillForegroundColor(new XSSFColor(Color.red));
		 redStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

		 XSSFRow row = sheet.getRow(1);
		 
		 int cellSize=row.getLastCellNum();
		 //冻结列
		 sheet.createFreezePane(3,2,3,2);
		 
		 sheet.addMergedRegion(new CellRangeAddress(0,0,cellSize,cellSize+4));
		 row = sheet.getRow(0);
		 XSSFCell cell = row.createCell(cellSize);
		 cell.setCellValue("天始统计时间(年-月-日-时:分-星期)");
		 
		 row = sheet.getRow(1);
		 
		 cell = row.createCell(cellSize);
		 cell.setCellValue("应采集量");
		 
		 cell = row.createCell(cellSize+1);
		 cell.setCellValue("实际采集量");
		
		 cell = row.createCell(cellSize+2);
		 cell.setCellValue("航班抓取总量");
		 
		 cell = row.createCell(cellSize+3);
		 cell.setCellValue("缺少量");
		 
		 cell = row.createCell(cellSize+4);
		 cell.setCellValue("缺少内容");
		 
		 sheet.addMergedRegion(new CellRangeAddress(2,2,cellSize,cellSize+4));
		 row = sheet.getRow(2);
		 cell = row.createCell(cellSize);
		 cell.setCellValue(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm")
					+ c.getDisplayName(Calendar.DAY_OF_WEEK,Calendar.ALL_STYLES, new Locale("zh_CN")));
		  int column=3;
		  
		  int allSize=HangxinDateUtil.getFlightDateSet().size()*HangxinDateUtil.getReturnDays().length;
		  
		  Map<String ,Integer> map=new LinkedHashMap<String ,Integer>();
		  for(String channel:countMap.keySet()){
			   int sum=0;
	        	for(String line:countMap.get(channel).keySet()){
	        		int size=0;
	        		int flightSize=0;
	        		boolean iscoun=true;
	        		for(String flightDate:countMap.get(channel).get(line).keySet()){
	        			
	        			for(String returnDate: countMap.get(channel).get(line).get(flightDate).keySet()){
	        				if(countMap.get(channel).get(line).get(flightDate).get(returnDate)>0){
	        					flightSize+=countMap.get(channel).get(line).get(flightDate).get(returnDate);
	        					size++;
	        				}else if(countMap.get(channel).get(line).get(flightDate).get(returnDate)<0){
	        					iscoun=false;
	        				}
	        			}
	        		
	        		}
	        		if(iscoun){
	        			 row = sheet.getRow(column);
						 cell=row.createCell(cellSize);
	        			 cell.setCellValue(allSize);
	        			 cell=row.createCell(cellSize+1);
	        			 if(size==0){
	        				 cell.setCellStyle(redStyle);//为0就设为红色
	        			 }
	        			 cell.setCellValue(size);
	        			 cell=row.createCell(cellSize+2);
	        			 cell.setCellValue(flightSize);
	        			 cell=row.createCell(cellSize+3);
	        			 cell.setCellValue(allSize-size);
	        			 sum+=size;
	        		}else{
	        			sum--;
	        		}
        			 column++;
	        	}
	        	map.put(channel, sum);
		  }
		  
		  int yingSize=0;
		  int totalSize=0;
		  for(String channel:countMap.keySet()){
			  if(map.get(channel)>=0){
				  row = sheet.getRow(column);
				  cell=row.createCell(cellSize);
	 			  cell.setCellValue(countMap.get(channel).size()*allSize);
	 			  cell=row.createCell(cellSize+1);
	 			  cell.setCellValue(map.get(channel));
	 			 if(map.get(channel)==0){
					 cell.setCellStyle(redStyle);
				 }
	 			  cell=row.createCell(cellSize+3);
				  cell.setCellValue(countMap.get(channel).size()*allSize-map.get(channel));
				  yingSize+=countMap.get(channel).size()*allSize;
				  totalSize+=map.get(channel);
				  column++;
				  row = sheet.getRow(column);
				  cell=row.createCell(cellSize+1);
				  cell.setCellValue(PriceUtil.round((double)map.get(channel)*100/(countMap.get(channel).size()*allSize), 2, BigDecimal.ROUND_HALF_UP)+"%");
				  column++;  
			  }else
				  column+=2;
			  
		  }
		  row = sheet.getRow(column);
		  cell=row.createCell(cellSize);
		  cell.setCellValue(yingSize);
		  cell=row.createCell(cellSize+1);
		  cell.setCellValue(totalSize);
		  cell=row.createCell(cellSize+3);
		  cell.setCellValue(yingSize-totalSize);
		  column++;
		  row = sheet.getRow(column);
		  cell=row.createCell(cellSize+1);
		  if(yingSize>1){
			  cell.setCellValue(PriceUtil.round((double)totalSize*100/yingSize, 2, BigDecimal.ROUND_HALF_UP)+"%"); 
		  }
		  column++;
		  if(null!=is){
	        	is.close();
	        }
		  if(null==file || !file.exists())
			  file=new File(fileName);
		  os = new FileOutputStream(file);  
		  workbook.write(os);
	      os.close();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
				try {
					if(null!=is){
						is.close();
					}
					if(null!=os){
					 os.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			
		}
		
		return file;
	}
   
	
	public File downloadFile(String remotePath,String fileName) {
		String address =ReportProperties.getAddress();
		int port= Integer.parseInt(null==ReportProperties.getPort()? "22":ReportProperties.getPort());
		String userName= ReportProperties.getUserName();
		String passWord =ReportProperties.getPassword();
		String path=ReportProperties.getPath();
		if(!path.endsWith("/")) path+="/";
		
		path=path.replace("webdata/", "");
		
		InputStream is = null;
		File file =new File(fileName);
		FtpConfig config =null;
		SFtpFileTransferClient sftpClient=null;
		boolean flag = false;
		try {
			config=new FtpConfig(address,port,userName,passWord);
			sftpClient=new SFtpFileTransferClient(config);
			try {
				flag = sftpClient.connect();
			} catch (FtpTransferException e) {
			}
			if (!flag) {
				log.error("connect sftp fail");
				return null;
			}
			String src=path+remotePath+fileName;
			if(!sftpClient.isFileExists(src)){
				return null;
			}
			is =sftpClient.downloadStream(src);
			ZipUtils.inputstreamtofile(is, file);
			sftpClient.disconnect();
		} catch (FtpTransferException e) {
			e.printStackTrace();
		}finally{
			if(null!=is){
				try {
					is.close();
				} catch (IOException e) {
					log.error(StringUtils.getStackTrace(e));
				}
			}
			if(null!=sftpClient){
				sftpClient.disconnect();
			}
		}
		
		return file;
	}
	
	private void uploadFile(File f,String remotePath) {
		String address =ReportProperties.getAddress();
		int port= Integer.parseInt(null==ReportProperties.getPort()? "22":ReportProperties.getPort());
		String userName= ReportProperties.getUserName();
		String passWord =ReportProperties.getPassword();
		String path=ReportProperties.getPath();
		if(!path.endsWith("/")) path+="/";
		path=path.replace("webdata/", "");
		//ftp连接配置
    	FtpConfig config =new FtpConfig(address,port,userName,passWord);
		SFtpFileTransferClient sftpClient=new SFtpFileTransferClient(config);
		InputStream in =null;
		boolean flag=false;
		try {
			try {
				flag = sftpClient.connect();
			} catch (Exception e) {
				log.error(StringUtils.getStackTrace(e));
				Thread.sleep(10 * 1000L);
				flag = sftpClient.connect();
			}
			if(null!=remotePath && remotePath.endsWith("/")){
				remotePath=remotePath.substring(0, remotePath.length()-1);
			}
			String dir=path+remotePath;
			if(flag){
				//如果目录不存在则创建
				String[] dirs=dir.split("/");
				StringBuffer buffer=new StringBuffer();
				for(String d:dirs){
					buffer.append(d+"/");
					if(!sftpClient.isDirectoryExists(buffer.toString())){
						sftpClient.makeDirectory(buffer.toString());
					}
				}
				in=new FileInputStream(f);
				
				sftpClient.upload(in, dir+"/"+f.getName());
				
				sftpClient.disconnect();
			}
		} catch (Exception e) {
			try {
				throw e;
			} catch (Exception e1) {
				log.error(StringUtils.getStackTrace(e));
			}
		}finally{
			if(null!=sftpClient){
				sftpClient.disconnect();	
			}
			try {
			if (in != null) {
				in.close();
			}
		} catch (Exception e) {
		}
		}
	}
}
